﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Text;
using Common;
using Model;
using BLL;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace weixin_test.Controllers
{
    public class TokenController : Controller
    {
        /// <summary>
        /// 微信认证
        /// </summary>
        /// <returns></returns>
        public string RenZhen()
        {
            string msg_str = "";
            try
            {
                if (Request.Method.ToUpper() == "GET")
                {
                    string signature = Request.Query["signature"];
                    if (!string.IsNullOrWhiteSpace(signature))
                    {
                        string timestamp = Request.Query["timestamp"];
                        string nonce = Request.Query["nonce"];
                        string echostr = Request.Query["echostr"];
                        string token = "5529d02578bf3cc560af";
                        var sha1 = System.Security.Cryptography.SHA1.Create();
                        byte[] byte_str = System.Text.Encoding.UTF8.GetBytes(timestamp  + nonce + token);
                        var hash = sha1.ComputeHash(byte_str);
                        string hash_str = BitConverter.ToString(hash).Replace("-", "");
                        if (hash_str.ToUpper() == signature.ToUpper())
                        {
                            msg_str = echostr;
                        }
                    }
                }
                else if (Request.Method.ToUpper() == "POST")
                {
                    WxUserInfoBLL userinfobll = new WxUserInfoBLL();
                    WeiXin_MsgEvent model = XmlHelper.DeserializeXmlToObject_WeiXin<WeiXin_MsgEvent>(Request.Body);
                    //事件处理
                    switch(model.Event)
                    {
                        case "subscribe":
                            // 用户未关注时，进行关注后的事件推送
                            if (userinfobll.IsExistOpenID(model.FromUserName))
                            {
                                //用户存在,只改变状态
                                userinfobll.UpdateSubscribe(model.FromUserName, 1);
                            }
                            else
                            {
                                //获取accesstoken
                                accesstoken token = AccessTokenBLL.GetWeiXinModel();
                                //新用户，获取用户信息
                                wx_userinfo userinfo = userinfobll.GetWxUserInfo(token.access_token, model.FromUserName);
                                if (userinfo != null)
                                {
                                    ReturnMessages rm = userinfobll.Add(userinfo);
                                }

                            }
                            
                            //关注的时候给用户发送消息
                            WeiXin_MsgEvent msg = new WeiXin_MsgEvent();
                            msg.Content = "您好，欢迎关注！";
                            msg.MsgType = "text";
                            msg.CreateTime = Utils.GetTimeStamp();
                            msg.ToUserName = model.FromUserName;
                            msg.FromUserName = model.ToUserName;
                            msg_str = XmlHelper.Serializer_WeiXin<WeiXin_MsgEvent>(msg);
                            break;
                        case "unsubscribe":
                            //用户取消关注
                            userinfobll.UpdateSubscribe(model.FromUserName, 0);
                            break;
                        case "TEMPLATESENDJOBFINISH":
                            //模版消息发送任务完成后的事件推送
                            LogHelper.Info("模版消息发送任务完成后的事件推送",JSONHelper.SerializeObject(model));
                            break;
                    }
                    //消息处理
                    switch(model.MsgType)
                    {
                        case "text":
                            //文本消息
                            if (model.Content == "红包")
                            {
                                //发送红包
                                Task.Run(() =>
                                {
                                    SendRedPackBLL sendbll = new SendRedPackBLL();
                                    sendbll.Send(model.FromUserName);
                                });
                                
                                //给用户发送消息
                                WeiXin_MsgEvent msg = new WeiXin_MsgEvent();
                                msg.Content = "红包发送中！";
                                msg.MsgType = "text";
                                msg.CreateTime = Utils.GetTimeStamp();
                                msg.ToUserName = model.FromUserName;
                                msg.FromUserName = model.ToUserName;
                                msg_str= XmlHelper.Serializer_WeiXin<WeiXin_MsgEvent>(msg);
                            }
                            else if(model.Content == "付款")
                            {
                                //企业付款
                                Task.Run(() =>
                                {
                                    EnterprisePaymentBLL ep = new EnterprisePaymentBLL();
                                    ep.Pay(model.FromUserName);
                                });
                                //给用户发送消息
                                WeiXin_MsgEvent msg = new WeiXin_MsgEvent();
                                msg.Content = "企业付款中！";
                                msg.MsgType = "text";
                                msg.CreateTime = Utils.GetTimeStamp();
                                msg.ToUserName = model.FromUserName;
                                msg.FromUserName = model.ToUserName;
                                msg_str = XmlHelper.Serializer_WeiXin<WeiXin_MsgEvent>(msg);
                            }
                            if (model.Content == "抽奖")
                            {
                                //给用户发送消息
                                WeiXin_MsgEvent msg = new WeiXin_MsgEvent();
                                msg.Content = "<a href=\"http://weixin.feng70.com/luck/index.html?openid="+ model.FromUserName + "&code="+ model.Content + "\">抽奖地址！</a>";
                                msg.MsgType = "text";
                                msg.CreateTime = Utils.GetTimeStamp();
                                msg.ToUserName = model.FromUserName;
                                msg.FromUserName = model.ToUserName;
                                msg_str = XmlHelper.Serializer_WeiXin<WeiXin_MsgEvent>(msg);
                            }
                            break;
                    }
                }
                else
                {
                    LogHelper.Debug("请求类型", Request.Method.ToUpper());
                }
                return msg_str;
            }
            catch(Exception e)
            {
                LogHelper.Error("server error", e.ToString());
                return msg_str;
            }
        }

        /// <summary>
        /// 拉取关注用户
        /// </summary>
        /// <returns></returns>
        public string GetOpendIDToUserInfo()
        {
            WxUserInfoBLL bll = new WxUserInfoBLL();
            return JSONHelper.SerializeObject(bll.GetOpendIDToUserInfo());
        }

        /// <summary>
        /// 给某人发送信息(客服接口,用户24小时内未跟公众号交互，会出现45015的错误)
        /// </summary>
        /// <returns></returns>
        public string SendMess()
        {
            try
            {
                //获取accesstoken
                accesstoken token = AccessTokenBLL.GetWeiXinModel();
                wx_message_text text_model = new wx_message_text();
                text_model.touser = "oLd4qwhdKI2fH9syBu4eR6tZENFU";
                text_model.text.content = "测试信息";
                LogHelper.Info("post值", JSONHelper.SerializeObject(text_model));
                string json = HttpServiceHelper.Post(JSONHelper.SerializeObject(text_model), "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token.access_token).Result;
                return json;
            }
            catch(Exception e)
            {
                LogHelper.Error("server error",e.ToString());
                return "fail";
            }
        }

        /// <summary>
        /// 发送模版消息
        /// </summary>
        /// <returns></returns>
        public string SendTemplateMess()
        {
            try
            {
                //获取accesstoken
                accesstoken token = AccessTokenBLL.GetWeiXinModel();
                wx_message_template_review template = new wx_message_template_review();
                
                template.data.first.value = "您好，工作人员已经通过您的审核。";
                template.data.keyword1.value = "测试类别";
                template.data.keyword2.value = "测试人员";
                template.data.keyword3.value = "感谢您的使用，审核已经通过，点击前往网站进行下一步审核流程。";
                template.data.keyword4.value = DateTime.Now.ToString();
                template.data.remark.value = "感谢您的使用，审核已经通过，点击前往网站进行下一步审核流程。";
                template.touser = "oLd4qwhdKI2fH9syBu4eR6tZENFU";
                template.url = "http://tarro.6otc.com";
                LogHelper.Info("post值", JSONHelper.SerializeObject(template));
                string json = HttpServiceHelper.Post(JSONHelper.SerializeObject(template), "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token.access_token).Result;
                return json;
            }
            catch (Exception e)
            {
                LogHelper.Error("server error", e.ToString());
                return "fail";
            }
        }


    }
}
